package com.example.moban.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.StringDef;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.moban.beans.StringDataListBean;
import com.example.moban.beans.UserInfoBean;

import com.rzhd.coursepatriarch.common.base.BaseApplication;
import com.rzhd.coursepatriarch.common.utils.CommonUtil;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @author yql
 * @date: 2018/7/2.
 */
public class SharedPreferenceUtils {

    private Context mContext;
    private final String TAG = getClass().getSimpleName();

    private static SharedPreferenceUtils sharedPreferenceUtils;
    /**
     * 创建一个写入器
     */
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    public SharedPreferenceUtils(Context context) {
        this.mContext = context;
        preferences = context.getSharedPreferences( BaseApplication.SHARED_DATA, Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

    public static SharedPreferenceUtils getInstance(Context context) {
        if (sharedPreferenceUtils == null) {
            synchronized (SharedPreferenceUtils.class) {
                if (sharedPreferenceUtils == null) {
                    sharedPreferenceUtils = new SharedPreferenceUtils(context);
                }
            }
        }
        return sharedPreferenceUtils;
    }

    @StringDef({SPCode.LOGIN, SPCode.LOGIN_INFO, SPCode.USER_INFO,
            SPCode.IS_RECEIVE_PUSH_MSG, SPCode.SECURITY_ISSUE_SETTING})
    @Retention(RetentionPolicy.SOURCE)
    public @interface SPCode {

        /**
         * 账号信息
         */
        String ACCOUNT = "ACCOUNT";

        /**
         * 账号信息
         */
        String PWD = "PWD";

        /**
         * 安全问题设置
         */
        String SECURITY_ISSUE_SETTING = "SECURITY_ISSUE_SETTING";

        /**
         * 第一次进入APP
         */
        String FIRST_LOGIN_APP = "FIRST_LOGIN_APP";

        /**
         * 登录状态
         */
        String LOGIN = "LOGIN";

        /**
         * 登录信息
         */
        String LOGIN_INFO = "LOGIN_INFO";

        /**
         * 登录信息
         */
        String USER_INFO = "USER_INFO";

        /**
         * 上次获取通知设置时间
         */
        String LAST_MESSAGE_TIME = "LAST_MESSAGE_TIME";

        /**
         * 是否接受推送消息
         */
        String IS_RECEIVE_PUSH_MSG = "isReceivePushMsg";

        /**
         * 最新版本号
         */
        String LATEST_VERSION_NUMBER = "LATEST_VERSION_NUMBER";

        /**
         * 微信支付回调
         */
        String WX_PAY_CALLBACK = "WX_PAY_CALLBACK";
        /**
         * 搜索历史
         */
        String SEARCH_HISTORY = "SEARCH_HISTORY";
        /**
         * 存储定位数据
         */
        String LOCATION_DATA = "LOCATION_DATA";
        /**
         * 新手引导
         */
        String NEW_PERSON_GUIDE = "NEW_PERSON_GUIDE";
        /**
         * 是否领取新人券
         */
        String IS_GOT_NEW_PERSON_COUPON = "IS_GOT_NEW_PERSON_COUPON";
        /**
         * 显示新人券弹窗日期
         */
        String SHOW_NEW_PERSON_COUPON_DIALOG_TIME = "SHOW_NEW_PERSON_COUPON_DIALOG_TIME";
        /**
         * 显示平台券弹窗日期
         */
        String SHOW_PLATFORM_COUPON_DIALOG_TIME = "SHOW_PLATFORM_COUPON_DIALOG_TIME";
        /**
         * 机构id
         */
        String MECHANISM_ID = "MECHANISM_ID";
        /**
         * 班级id
         */
        String CLASS_ID = "CLASS_ID";
        /**
         * 打开APP的时间
         */
        String OPEN_APP_DATE_TIME = "OPEN_APP_DATE_TIME";
        /**
         * 阿里支付结果
         */
        String ALI_PAY_RESULT = "ALI_PAY_RESULT";
    }

    /**
     * 设置登录信息
     *
     * @param isLogin
     */
    public void setLogin(boolean isLogin) {
        editor.putBoolean(SPCode.LOGIN, isLogin);
        editor.commit();
    }

    /**
     * 获取登录信息
     *
     * @return
     */
    public boolean getLogin() {
        return preferences.getBoolean(SPCode.LOGIN, false);
    }

    /**
     * 存储登录账号
     */
    public void saveLoginAccount( String account , String pwd ){
        editor.putString(SPCode.ACCOUNT, account );
        editor.putString(SPCode.PWD, pwd );
        editor.commit();
    }

    /**
     * 获取登录账号
     * @return
     */
    public String getAccount(){
        return preferences.getString( SPCode.ACCOUNT , "" );
    }

    /**
     * 获取密码
     * @return
     */
    public String getPwd(){
        return preferences.getString( SPCode.PWD , "" );
    }

    /**
     * 设置安全问题
     * @param isSet
     */
    public void setSecurityIssue( boolean isSet ){
        editor.putBoolean(SPCode.SECURITY_ISSUE_SETTING, isSet );
        editor.commit();
    }

    /**
     * 是否设置安全问题
     * @return
     */
    public boolean isSetSecurityIssue(){
        return preferences.getBoolean( SPCode.SECURITY_ISSUE_SETTING , false );
    }

    /**
     * list转换成字符串
     * @param searchHistory
     * @return
     */
    public String listToJsonStr( List<String> searchHistory ){
        StringDataListBean bean = new StringDataListBean( searchHistory );
        JSONObject json = (JSONObject) JSON.toJSON( bean );
        return json.toJSONString();
    }

    public List<String> jsonStrToList( String jsonStr ){
        if( TextUtils.isEmpty( jsonStr )){
            return null;
        }
        StringDataListBean bean = JSON.parseObject( jsonStr , StringDataListBean.class );
        if( bean == null ){
            return null;
        }
        return bean.getData();
    }

    /**
     * 存储搜索历史记录
     * @param searchHistory
     */
    public void saveSearchHistory( List<String> searchHistory ){
        editor.putString( SPCode.SEARCH_HISTORY, listToJsonStr(searchHistory) );
        editor.commit();
    }


    /**
     * 第一次进入app
     * @param
     */
    public void setFirstApp(  ){
        editor.putString( SPCode.FIRST_LOGIN_APP, "1" );
        editor.commit();
    }
    /**
     * 获取第一次进入app
     * @param
     */
    public String getFirstApp(  ){
        String first = preferences.getString( SPCode.FIRST_LOGIN_APP , "0" );
        return first;
    }


    /**
     * 获取
     * @return
     */
    public List<String> getSearchHistory(){
        String string = preferences.getString( SPCode.SEARCH_HISTORY , "" );
        return jsonStrToList( string );
    }

    /**
     * set转换成list
     * @param stringSet
     * @return
     */
    private List<String> setToList( Set<String> stringSet ){
        if( stringSet == null ){
            return null;
        }
        List<String> list = new ArrayList<>();
        for( String str : stringSet ){
            list.add( str );
        }
        return list;
    }

    /**
     * list转换成set
     * @param stringList
     * @return
     */
    private Set<String> listToSet( List<String> stringList ){
        if( stringList == null ){
            return null;
        }
        Set<String> set = new HashSet<>();
        for( String str : stringList ){
            set.add( str );
        }
        return set;
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        String loginInfo = preferences.getString(SPCode.LOGIN_INFO, "");
        if (TextUtils.isEmpty(loginInfo)) {
            return "";
        }
        UserInfoBean.DataBean loginBean = JSON.parseObject(loginInfo, UserInfoBean.DataBean.class);
        if (loginBean == null ) {
            return "";
        }
        return loginBean.getToken();
    }

    /**
     * 获取登录用户的id
     *
     * @return
     */
    public String getUserId() {
        String loginInfo = preferences.getString(SPCode.LOGIN_INFO, "");
        if (TextUtils.isEmpty(loginInfo)) {
            return "";
        }
        UserInfoBean.DataBean loginBean = JSON.parseObject(loginInfo, UserInfoBean.DataBean.class);
        if (loginBean == null ) {
            return "";
        }
        return ""+loginBean.getId();
    }


    /**
     * 设置登录信息
     *
     * @param loginInfo
     */
    public void setLoginInfo(String loginInfo) {
        editor.putString(SPCode.LOGIN_INFO, loginInfo);
        editor.commit();
    }

    /**
     * 设置登录信息
     *
     * @param userInfo
     */
    public void setLoginInfo(UserInfoBean.DataBean userInfo) {
        if (userInfo != null) {
            String userInfoJson = JSON.toJSONString(userInfo);
            editor.putString(SPCode.LOGIN_INFO, userInfoJson);
        } else {
            editor.putString(SPCode.LOGIN_INFO, "");
        }
        editor.commit();
    }

    /**
     * 获取登录信息
     */
    public String getLoginInfo() {
        return preferences.getString(SPCode.LOGIN_INFO, "" );
    }

    /**
     * 获取登录bean
     *
     * @return
     */
    public UserInfoBean.DataBean getLoginBean() {
        String loginInfo = getLoginInfo();
        if (TextUtils.isEmpty(loginInfo)) {
            return null;
        }
        UserInfoBean.DataBean loginBean = JSON.parseObject(loginInfo, UserInfoBean.DataBean.class);
        return loginBean;
    }

    /**
     * 获取登录用户的手机号
     * @return
     */
    public String getPhoneNumber(){
        UserInfoBean.DataBean loginBean = getLoginBean();
        if( loginBean == null ){
            return "";
        }
        return loginBean.getPhone();
    }

    /**
     * 是否接受推送消息
     *
     * @return
     */
    public boolean isReceivePushMsg() {
        return preferences.getBoolean(SPCode.IS_RECEIVE_PUSH_MSG, true);
    }

    public void setIsReceivePushMsg(boolean isReceivePushMsg) {
        editor.putBoolean(SPCode.IS_RECEIVE_PUSH_MSG, isReceivePushMsg);
        editor.commit();
    }

    /**
     * 设置用户信息
     *
     * @param userInfo
     */
    public void setUserInfo(UserInfoBean.DataBean userInfo) {
        if (userInfo != null) {
            String userInfoJson = JSON.toJSONString(userInfo);
            editor.putString(SPCode.USER_INFO, userInfoJson);
        } else {
            editor.putString(SPCode.USER_INFO, "");
        }
        editor.commit();
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public UserInfoBean.DataBean getUserInfo() {
        String userInfoJson = preferences.getString(SPCode.USER_INFO, "");
        UserInfoBean.DataBean dataBean = null;
        if (TextUtils.isEmpty(userInfoJson)) {
            return null;
        } else {
            dataBean = JSON.parseObject(userInfoJson, UserInfoBean.DataBean.class);
            return dataBean;
        }
    }


    /**
     * 获取上次通知时间
     *
     * @return
     */
    public boolean getLastMessageTime() {
        String lastTime = preferences.getString(SPCode.LAST_MESSAGE_TIME, "");
        String time = MyUtils.getTime();
        if (TextUtils.isEmpty(lastTime)) {
            editor.putString(SPCode.LAST_MESSAGE_TIME, time);
            return true;
        } else {
            boolean isToday =false;
            try {
                 isToday = MyUtils.handleDate(Long.valueOf(lastTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }catch (Exception e){
                FeiLogUtil.e("fei",e.toString());
            }
            if (isToday){
                return false;
            }else {
                return true;
            }


        }
    }


    /**
     * 存储当前机构id
     * @param mechanismId
     */
    public void saveCurrentMechanismId( String mechanismId ){
        editor.putString(SPCode.MECHANISM_ID, mechanismId  );
        editor.commit();
    }

    /**
     * 获取当前机构id
     */
    public String getCurrentMechanismId(){
        return preferences.getString(SPCode.MECHANISM_ID , "" );
    }

    /**
     * 存储当前班级id
     * @param classId
     */
    public void saveCurrentClassId( String classId ){
        editor.putString(SPCode.CLASS_ID, classId  );
        editor.commit();
    }

    /**
     * 获取当前班级id
     */
    public String getCurrentClassId(){
        return preferences.getString(SPCode.CLASS_ID , "" );
    }

    /**
     * 设置微信支付回调信息
     *
     * @param info
     */
    public void setWXPayCallback(String info) {
        editor.putString(SPCode.WX_PAY_CALLBACK, info);
        editor.commit();
    }

    /**
     * 获取微信支付回到信息
     *
     * @return
     */
    public String getWXPayCallback() {
        return preferences.getString(SPCode.WX_PAY_CALLBACK, "");
    }

    /**
     * 设置最新版本号信息
     *
     * @param info
     */
    public void setLatestVersionNumber(String info) {
        editor.putString(SPCode.LATEST_VERSION_NUMBER, info);
        editor.commit();
    }

    /**
     * 获取最新版本号
     *
     * @return
     */
    public String getLatestVersionNumber() {
        return preferences.getString(SPCode.LATEST_VERSION_NUMBER, "");
    }

    /**
     * 设置用户未读消息数量
     *
     * @param messageBean 接收的消息数量
     */
//    public void setNotifyMessage(UserInfoBean.DataBean messageBean) {
//        UserInfoBean.DataBean userInfo = getUserInfo();
//        if (userInfo == null) {
//            return;
//        }
//        userInfo.setChatCount(messageBean.getChatCount());
//        userInfo.setBeChatCount(messageBean.getBeChatCount());
//        userInfo.setMessageCount(messageBean.getMessageCount());
//        userInfo.setProductCount(messageBean.getProductCount());
//        userInfo.setAllChatCount(messageBean.getAllChatCount());
//        setUserInfo(userInfo);
//    }

    /**
     * 获取设备号并存储(不需要权限)
     */
    public String getDeviceCodeAndSave() {
        //获取设备号
        String identify = preferences.getString("identify", "");
        if ( TextUtils.isEmpty( identify )) {
            identify = CommonUtil.getUniqueId( mContext );
            SharedPreferences.Editor edit = preferences.edit();
            edit.putString( "identify" , identify );
        }
        return identify;
    }

    /**
     *
     * @param locationData
     */
    public void saveLocationDatas( String locationData ){
        editor.putString(SPCode.LOCATION_DATA, locationData );
        editor.commit();
    }

    /**
     * 获取定位数据
     * @return
     */
    public String getLocationDatas(){
        return preferences.getString( SPCode.LOCATION_DATA , "");
    }

    /**
     * 存储当前打开APP的日期
     * @param dateTime
     */
    public void saveOpenAppDateTime( String dateTime ){
        editor.putString(SPCode.OPEN_APP_DATE_TIME, dateTime );
        editor.commit();
    }

    /**
     * 获取当前打开APP的日期
     */
    public String getOpenAppDateTime(){
        return preferences.getString( SPCode.OPEN_APP_DATE_TIME , "" );
    }

    /**
     * 阿里支付结果
     * @param type  1--成功,0失败
     */
    public void setAliPayResult( String type ){
        editor.putString(SPCode.ALI_PAY_RESULT, type );
        editor.commit();
    }

    /**
     * 阿里支付结果
     */
    public String getAliPayResult(){
        return preferences.getString( SPCode.ALI_PAY_RESULT , "" );
    }
}
